package com.woniuxy.service.impl;

import com.woniuxy.dao.UserDao;
import com.woniuxy.entity.*;
import com.woniuxy.service.IUserService;
import com.woniuxy.shiro.jwt.JWTUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ylr
 * @time 2022/05/30 20:32:21
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserDao userDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResponseEntity login(String username, String password) {
        SimpleHash simpleHash = new SimpleHash("MD5", password, username);
        String newPassword = simpleHash.toHex();
        User user = userDao.login(username, newPassword);
        String account = user.getUsername();
        String passwordd = user.getPassword();
        //调用jwt工具类生成token
        String token = JWTUtils.sign(account, password);
        //把token当作key,返回的对象当作值，存入redis中
        redisTemplate.opsForValue().set(token, user);
        //设置这个token的过期时间
        redisTemplate.expire(token, 30, TimeUnit.MINUTES);
        ResponseEntity responseEntity = new ResponseEntity(user);
        responseEntity.putKey("token", token);
        return responseEntity;
    }

    @Override
    public Set<String> findRoles(String username) {
        return userDao.findRoles(username);
    }

    @Override
    public Set<String> findPerms(String username) {
        return userDao.findPerms(username);
    }

    @Override
    public List<Test> findUsers(Map<String, Object> map) {
        return userDao.findUsers(map);
    }

    @Override
    public ResponseEntity addUser(Map map) {
        User user = new User();
        user.setPassword((String) map.get("password"));
        user.setUsername((String) map.get("username"));
        Classs classs = new Classs();
        classs.setName((String) map.get("classs"));
        user.setClasss(classs);
        Role role = new Role();
        role.setName((String) map.get("role"));
        user.setRole(role);
        user.setStatus("y");
        int i = userDao.addUser(user);

        if (i > 0) {
            return ResponseEntity.SUCCESS;
        } else {
            return ResponseEntity.ERROR;
        }

    }


}
